package org.xxpay.manage.alipay.cash.ctrl;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.xxpay.core.common.constant.Constant;
import org.xxpay.core.common.constant.MchConstant;
import org.xxpay.core.common.domain.XxPayPageRes;
import org.xxpay.core.common.domain.XxPayResponse;
import org.xxpay.core.entity.AlipayCash;
import org.xxpay.core.entity.AlipayCashDetail;
import org.xxpay.manage.common.ctrl.BaseController;
import org.xxpay.manage.common.service.CommonService;
import org.xxpay.manage.common.service.RpcCommonService;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping(Constant.MGR_CONTROLLER_ROOT_PATH + "/alipayCash")
public class AlipayCashController extends BaseController {

    @Autowired
    private CommonService commonService;

    @Autowired
    private RpcCommonService rpcCommonService;

    @RequestMapping("/list")
    @ResponseBody
    public ResponseEntity<?> list(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        AlipayCash record = getObject(param, AlipayCash.class);
        int count = commonService.alipayCashService.count(record);
        if(count == 0) return ResponseEntity.ok(XxPayPageRes.buildSuccess());
        List<AlipayCash> recordList = commonService.alipayCashService.select((getPageIndex(param) - 1) * getPageSize(param), getPageSize(param), record);
        return ResponseEntity.ok(XxPayPageRes.buildSuccess(recordList, count));
    }


    @RequestMapping("/get")
    @ResponseBody
    public ResponseEntity<?> get(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        Integer id = getIntegerRequired(param, "id");
        AlipayCash record = commonService.alipayCashService.findById(id);
        return ResponseEntity.ok(XxPayResponse.buildSuccess(record));
    }


    /** 创建红包 **/
    @RequestMapping("/create")
    @ResponseBody
    public ResponseEntity<?> create(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        handleParamAmount(param, "totalMoney"); //元转换为分
        AlipayCash record = getObject(param, AlipayCash.class);
        Integer alipayCashId = rpcCommonService.rpcXxPayAlipayCashService.createAlipayCash(record);
        AlipayCash dbRecord = commonService.alipayCashService.findById(alipayCashId);

        JSONObject result = new JSONObject();
        if(dbRecord.getTaskStatus() == AlipayCash.TASK_STATUS_CREATE_SUCCESS && //任务创建成功  & 支付宝状态为待支付
        AlipayCash.ALIPAY_STATUS_CREATED.equals(dbRecord.getAlipayStatus())){
            result.put("isSuccess", true);
            result.put("alipayCashId", alipayCashId);
            result.put("payUrl", dbRecord.getAlipayPayUrl());
        }else{
            result.put("isSuccess", false);
            result.put("errorMsg", dbRecord.getAlipayErrorMsg());
        }
        return ResponseEntity.ok(XxPayResponse.buildSuccess(result));
    }

    /** 更新最新支付宝状态 **/
    @RequestMapping("/updateAlipayStatus")
    @ResponseBody
    public ResponseEntity<?> updateAlipayStatus(Integer cashId) {

        String alipayStatus = rpcCommonService.rpcXxPayAlipayCashService.updateInfoFromAlipay(cashId); //支付宝最新状态
        return  ResponseEntity.ok(XxPayResponse.buildSuccess(alipayStatus));

    }


    /** 触发领取红包动作 **/
    @RequestMapping("/tiggerAlipayCash")
    @ResponseBody
    public ResponseEntity<?> tiggerAlipayCash(Integer cashId) {

        rpcCommonService.rpcXxPayAlipayCashService.triggerAlipayCash(cashId);
        return  ResponseEntity.ok(XxPayResponse.buildSuccess(true));

    }


    /** 取消发放 **/
    @RequestMapping("/cancelAlipayCash")
    @ResponseBody
    public ResponseEntity<?> cancelAlipayCash(Integer cashId) {

        //先查询支付宝方的最新状态
        String alipayStatus = rpcCommonService.rpcXxPayAlipayCashService.updateInfoFromAlipay(cashId); //支付宝最新状态

        //[已打款] [活动已开始] [活动已暂停]  调起支付宝接口将活动变更为 【已结束】
        if( AlipayCash.ALIPAY_STATUS_PAID.equals(alipayStatus) || AlipayCash.ALIPAY_STATUS_READY.equals(alipayStatus) ||
            AlipayCash.ALIPAY_STATUS_PAUSE.equals(alipayStatus)){
            String errMsg = rpcCommonService.rpcXxPayAlipayCashService.modifyStatus(cashId, AlipayCash.ALIPAY_STATUS_CLOSED);
            if(errMsg != null){ //操作失败
                return ResponseEntity.ok(XxPayResponse.buildSuccess(errMsg));
            }
        }

        //更新支付平台状态为【已取消】， 明细状态为【取消】
        commonService.alipayCashService.cancel(cashId);
        return ResponseEntity.ok(XxPayResponse.buildSuccess());


    }

	@RequestMapping("/detailList")
    @ResponseBody
    public ResponseEntity<?> detailList(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        AlipayCashDetail detail = getObject(param, AlipayCashDetail.class);
        if(getUser().getIsSuperAdmin() != MchConstant.PUB_YES) detail.setBelongUserId(getUser().getId()); //非超管需要添加查询条件
        int count = commonService.alipayCashDetailService.count(detail);
        if(count == 0) return ResponseEntity.ok(XxPayPageRes.buildSuccess());
        List<AlipayCashDetail> detailList = commonService.alipayCashDetailService.select((getPageIndex(param) - 1) * getPageSize(param), getPageSize(param), detail);
        return ResponseEntity.ok(XxPayPageRes.buildSuccess(detailList, count));
    }


    /**
     * 统计红包明细发放总额
     * @return
     */
    @RequestMapping("/statistic")
    @ResponseBody
    public ResponseEntity<?> grantAmount(HttpServletRequest request) {

        JSONObject param = getJsonParam(request);
        AlipayCashDetail detail = getObject(param, AlipayCashDetail.class);
        if(getUser().getIsSuperAdmin() != MchConstant.PUB_YES) detail.setBelongUserId(getUser().getId()); //非超管需要添加查询条件

        //今日 /昨日 发放总额
        Map amountMap = commonService.alipayCashDetailService.selectTotalCashAmount(detail);
        return ResponseEntity.ok(XxPayResponse.buildSuccess(amountMap));
    }


}
